package com.yf.dmp.service;

import com.alibaba.fastjson.JSON;
import com.yf.dmp.bean.QueryInfo;
import com.yf.dmp.bean.User;
import com.yf.dmp.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao uDao;

    public String getUser(QueryInfo queryInfo){
        int num = uDao.getUserCount("%" + queryInfo.getQuery() + "%");
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();
        List<User> us = uDao.getUser("%" + queryInfo.getQuery() + "%", pageStart, queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("num", num);
        res.put("data", us);
        String jsonstr = JSON.toJSONString(res);
        return jsonstr;
    };

    public int addUser(User us){
        us.setPassword(DigestUtils.md5DigestAsHex(us.getPassword().getBytes()));
        us.setState(false);
        int i = uDao.addUser(us);
        return i;
    };
    public int getUserCount(String code){
        return uDao.getUserCount(code);
    };
    public int deleteUserById(int id){
        System.out.println("删除用户:="+id);
        return uDao.deleteUserById(id);
    };
    public User getUpdateUser(int id){
        return uDao.getUpdateUser(id);
    };
    public int updateUser(User us){
        return uDao.updateUser(us);
    };
    public int updateUserState(Integer id,boolean state){
        return uDao.updateState(id,state);
    }
    public int updatePassword(Integer id,String password,String newpassword){
        User user = uDao.getUpdateUser(id);
        if(user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())) ){
            int i = uDao.updatePassword(id,DigestUtils.md5DigestAsHex(newpassword.getBytes()));
            return  i;
        }else {
            return 0;
        }
    }
}
